package com.sunducation.wts.viewmodel

import android.app.Application
import android.content.Context
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import java.util.*

//viewmodel中传上下文必须是Application,否则会出现内存泄漏
class TimerViewModel2 constructor(application: Application) : AndroidViewModel(application) {
    private var timer : Timer? = null
    private var currentSecond = 0
    private lateinit var mApplication: Application;
    init {
        mApplication = application;
    }

    override fun onCleared() {
        super.onCleared()
        timer?.cancel()
    }
    fun startTiming() {
        Log.e("上下文", mApplication.toString())
        if(timer == null) {
            currentSecond = 0
            timer = Timer()
            val timerTask : TimerTask = object :TimerTask() {
                override fun run() {
                    currentSecond++
                    onTimeChangeListener?.onTimeChanged(currentSecond);
                }
            }
            timer?.schedule(timerTask,1000,1000);
        }
    }

    private var onTimeChangeListener : OnTimeChangeListener? = null;

    public fun setOnTimeChangeListener(onTimeChangeListener : OnTimeChangeListener) {
        this.onTimeChangeListener = onTimeChangeListener;
    }

    public interface OnTimeChangeListener{
        fun onTimeChanged(second : Int)
    }
}